import { forwardRef, useRef, useImperativeHandle, ForwardedRef } from "react";

import { useComponent, fixInputValue, CommonComponentProps } from "../factory";

import "./index.css";

interface InputProps extends CommonComponentProps {
  foo?: any;
}

interface InputInstance {
  input: HTMLInputElement | null;
}

const InnerInput = (props: InputProps, ref: ForwardedRef<InputInstance>) => {
  const {
    className,
    style,
    val: value,
    action,
  } = useComponent({
    ...props,
    wrapperCls: "custom-input",
  });

  const inputRef = useRef<HTMLInputElement>(null);

  // 将原生input节点暴露给外部
  useImperativeHandle(ref, () => {
    return {
      input: inputRef.current,
    };
  });

  return (
    <input
      ref={inputRef}
      className={className}
      style={style}
      value={fixInputValue(value)}
      onChange={(e) => action(e.target.value)}
    />
  );
};

const Input = forwardRef(InnerInput);

export default Input;
